package cn.htsyb.synergy.tester.frame;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;

public class FtpClientFrame {
    protected final static Log log = LogFactory.getLog(FtpClientFrame.class);
    private static String serverIp;
    private static int serverPort;
    private static String loginName;
    private static String password;
    private static String ftpServerFolder;
    private static FTPClient ftpClient;
    private static FileOutputStream fos = null;
    private static FileInputStream fis = null;

    /**
     * 重要信息配置，并初始化FTPClient
     *
     * @param serverIp
     * @param serverPort
     * @param loginName
     * @param password
     * @param ftpServerFolder 服务器设置的存储根目录是： F:\FTPServer,如果想将文件保存在： F:\FTPServer\report\,则需要将此字段填为： /report/
     */
    public static void config(String serverIp, int serverPort, String loginName, String password, String ftpServerFolder) {
        FtpClientFrame.serverIp = serverIp;
        FtpClientFrame.serverPort = serverPort;
        FtpClientFrame.loginName = loginName;
        FtpClientFrame.password = password;
        FtpClientFrame.ftpServerFolder = ftpServerFolder;
        ftpClient = new FTPClient();
    }


    /**
     * 通过FTP上传一个文件到服务器指定目录<br>
     * 通过Log4j打印跟踪日志<br>
     * <em>编写日期：2014年2月14日 15:25</em>
     *
     * @author mengfeiyang
     * @version 1.0
     * @since JDK 1.7 及以上
     */
    public static String FTPUpload(String FilePath) {
        try {
            String uploadResult;
            ftpClient.connect(serverIp, serverPort);
            ftpClient.login(loginName, password);
            log.info(ftpClient.getReplyString());
            File srcFile = new File(FilePath);
            fis = new FileInputStream(srcFile);
            //设置上传目录 
            ftpClient.changeWorkingDirectory(ftpServerFolder);
            ftpClient.setBufferSize(1024);
            ftpClient.setControlEncoding("GBK");
            //设置文件类型（二进制） 
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

            String[] FilePaths = FilePath.split("\\\\");
            String fileName = FilePaths[FilePaths.length - 1];

            ftpClient.storeFile(new String(fileName.getBytes("GBK"), StandardCharsets.ISO_8859_1), fis);// 转换后的目录名或文件名。, fis);
            if (ftpClient.getReplyString().contains("complete")) {
                uploadResult = "上传文件：" + fileName + " 到FTP服务器成功";
                log.info(ftpClient.getReplyString());
            } else {
                uploadResult = ftpClient.getReplyString();
                log.info(ftpClient.getReplyString());
            }
            return uploadResult;
        } catch (Exception e) {
            return "上传文件 到FTP服务器失败！异常信息：" + e.getMessage();
        }
    }

    /**
     * 通过FTP服务器指定目录下载一个文件到本地指定目录,
     * 只需指定FTPServer的指定文件名即可
     * <em>编写日期：2014年2月14日 15:25</em>
     *
     * @author mengfeiyang
     * @version 1.0
     * @since JDK 1.7 及以上
     */
    public static String FTPDownload(String FileName, String localPath) {
        try {
            ftpClient.connect(serverIp, serverPort);
            ftpClient.login(loginName, password);
            log.info(ftpClient.getReplyString());
            String remoteFileName = ftpServerFolder + FileName;
            fos = new FileOutputStream(localPath + File.pathSeparator + FileName);

            ftpClient.setBufferSize(1024);
            //设置文件类型（二进制） 
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.retrieveFile(remoteFileName, fos);
            log.info(ftpClient.getReplyString());
            return "从FTP服务器下载文件：" + FileName + " 到本地成功";
        } catch (Exception e) {
            return "从FTP服务器下载文件失败！异常信息：" + e.getMessage();
        }
    }

    public static void disconnect() {
        try {
            IOUtils.closeQuietly(fos);
            IOUtils.closeQuietly(fis);
            ftpClient.disconnect();
            log.info(ftpClient.getReplyString());
        } catch (Exception e) {
        }
    }
}
